package com.tanhua.dubbo.server.api;

import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.pojo.Sound;
import com.tanhua.dubbo.server.service.IdService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import javax.validation.constraints.Max;

@Service(version = "1.0.0")
public class SoundApiImpl implements SoundApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdService idService;

    @Override
    public String saveSound(Sound sound) {

        if (null == sound.getUserId()) {
            return null;
        }
        sound.setId(ObjectId.get());
        sound.setCreated(System.currentTimeMillis());
        sound.setSid(idService.createId("sound", sound.getId().toHexString()));
        Sound save = this.mongoTemplate.save(sound);

        return save.getId().toHexString();
    }

    @Override
    public Sound querySoundBySid(Long sid) {

        Query query = Query.query(Criteria.where("sid").is(sid));
        Sound sound = this.mongoTemplate.findOne(query, Sound.class);
        return sound;
    }

    @Override
    public Long querySoundCountExceptRegister(Long userId) {
        Query query = Query.query(Criteria.where("userId").ne(userId));
        return this.mongoTemplate.count(query, Sound.class);
    }

    @Override
    public Long queryMaxSoundSid() {
        Query query = new Query();
        query.with(Sort.by(Sort.Order.desc("sid"))).limit(1);
        return this.mongoTemplate.findOne(query,Sound.class).getSid();
    }
}
